const log4js = require('koa-log4')
const path = require('path')
const fs = require('fs')
const basePath = path.resolve(__dirname, '../logs')
const errorPath = basePath + '/errors/'
const resPath = basePath + '/responses/'
const accsPath = basePath + '/access/'
// const errorFilename = errorPath + '/error'
// const resFilename = resPath + '/response'

/**
 * 确定目录是否存在，如果不存在则创建目录
 */
const confirmPath = function (pathStr) {
    if (!fs.existsSync(pathStr)) {
        fs.mkdirSync(pathStr)
        // console.log('createPath: ' + pathStr);
    }
}

log4js.configure({
    appenders: {
        access: {
            type: 'dateFile',
            filename: accsPath,
            pattern: 'yyyy-MM-dd.log',
            alwaysIncludePattern: true
        },
        app: {
            category: 'log_date',
            type: 'dateFile',
            filename: resPath,
            maxLogSize: 10 * 1000 * 1000,
            numBackups: 3,
            pattern: 'yyyy-MM-dd.log',
            alwaysIncludePattern: true
        },
        errorFile: {
            type: 'dateFile',
            filename: errorPath,
            pattern: 'yyyy-MM-dd.log',
            alwaysIncludePattern: true
        },
        errors: {
            type: 'logLevelFilter',
            level: 'error',
            appender: 'errorFile'
        }
    },
    categories: {
        default: {
            appenders: ['app', 'errors'],
            level: 'info'
        },
        http: {
            appenders: ['access'],
            level: 'info'
        }
    },
    replaceConsole: true
})

// 创建log的根目录'logs'
if (basePath) {
    confirmPath(basePath)
    // 根据不同的logType创建不同的文件目录
    confirmPath(errorPath)
    confirmPath(resPath)
}

module.exports = log4js